//
//  RegisterSetUserInfoVC.m
//  SHShopping
//
//  Created by 坤鼎 on 2019/9/5.
//  Copyright © 2019 kunding. All rights reserved.
//

#import "RegisterSetUserInfoVC.h"
#import <AVFoundation/AVFoundation.h>
#import "MainTabBarVC.h"

@interface RegisterSetUserInfoVC () <UINavigationControllerDelegate, UIImagePickerControllerDelegate, UITextFieldDelegate>

@property (nonatomic, strong) UIButton *btnUserIcon;

@property (nonatomic, strong) UITextField *tf;

@property (nonatomic, strong) UIButton *btnOK;
/**
 UITextField 字符最大长度
 */
@property (nonatomic, assign) NSInteger textLongLength;
/**
 UITextField 字符最小长度
 */
@property (nonatomic, assign) NSInteger textShortLength;
/**
 用户头像
 */
@property (nonatomic, copy) NSString *avatarUrl;

@end

@implementation RegisterSetUserInfoVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.textShortLength = 2;
    self.textLongLength = 15;
    [self setNav];
    [self initView];
}

- (void)initView {
    
    CGFloat bage = ADAPT_W(23);
    
    self.btnUserIcon = [[UIButton alloc] initWithFrame:CGRectMake((SCREEN_WIDTH - 87) / 2, 53, 87, 87)];
    UILabel *lbTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, GetViewYH(self.btnUserIcon) + 9, SCREEN_WIDTH, 20)];
   
    UIView *tfBackgroundView = [[UIView alloc] initWithFrame:CGRectMake(bage, GetViewYH(lbTitle) + 33, SCREEN_WIDTH - bage * 2, 54)];
    self.tf = [[UITextField alloc] initWithFrame:CGRectMake(bage, 0, GetViewWidth(tfBackgroundView) - bage * 2, 54)];
    
    self.btnOK = [[UIButton alloc] initWithFrame:CGRectMake(bage, GetViewYH(tfBackgroundView) + 18, SCREEN_WIDTH - bage * 2, 54)];
    UIButton *btnSkip = [[UIButton alloc] initWithFrame:CGRectMake(bage, GetViewYH(self.btnOK) + 18, SCREEN_WIDTH - bage * 2, 54)];
    UIButton *btnBottom = [[UIButton alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 44 - 32 - kNavBarAndStatusBarHeight, SCREEN_WIDTH, 44)];
    
    [self.view addSubview:self.btnUserIcon];
    [self.view addSubview:lbTitle];
    
    [self.view addSubview:tfBackgroundView];
    [tfBackgroundView addSubview:self.tf];
    
    [self.view addSubview:self.btnOK];
    [self.view addSubview:btnSkip];
    [self.view addSubview:btnBottom];
    
    [_btnUserIcon setImage:ImageNamed(@"login_AddIcon") forState:UIControlStateNormal];
    [_btnUserIcon addTarget:self action:@selector(actionIcon) forControlEvents:UIControlEventTouchUpInside];
    _btnUserIcon.layer.cornerRadius = 43.5;
    _btnUserIcon.layer.masksToBounds = YES;
    
    lbTitle.text = @"上传头像";
    lbTitle.textColor = UIColorFromRGB(0x333333);
    lbTitle.textAlignment = YES;
    lbTitle.font = FONT(14);
    
    tfBackgroundView.layer.cornerRadius = 27;
    tfBackgroundView.layer.borderWidth = 1;
    tfBackgroundView.layer.borderColor = UIColorFromRGB(0x999999).CGColor;
    tfBackgroundView.layer.masksToBounds = YES;
    
    self.tf.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.tf.delegate = self;
    self.tf.placeholder = @"   请输入用户名";
    self.tf.text = [UserManager sharedUserManager].userInfo.nickName;
    
    [self.btnOK addTarget:self action:@selector(actionSkip) forControlEvents:UIControlEventTouchUpInside];
    [self.btnOK setTitle:@"完成" forState:UIControlStateNormal];
    [self.btnOK gradientViewColorArray:@[] pointArr:@[]];
    self.btnOK.alpha = 0.6;
    self.btnOK.userInteractionEnabled = NO;
    
    btnSkip.titleLabel.font = FONT(19);
    [btnSkip setTitle:@"跳过" forState:UIControlStateNormal];
    [btnSkip addTarget:self action:@selector(actionSkip) forControlEvents:UIControlEventTouchUpInside];
    [btnSkip setTitleColor:UIColorFromRGB(0x555555) forState:UIControlStateNormal];
    
    NSMutableAttributedString * attriStr = [[NSMutableAttributedString alloc] initWithString:@"登录即代表阅读并同意服务协议"];
    [attriStr addAttribute:NSFontAttributeName value:FONT_BOLD(13) range:NSMakeRange(10, 4)];
    [btnBottom setAttributedTitle:attriStr forState:UIControlStateNormal];
    btnBottom.titleLabel.font = FONT(12);
    [btnBottom addTarget:self action:@selector(actionAgreement) forControlEvents:UIControlEventTouchUpInside];
    
    if (self.isLogin) {
        [self.btnOK setTitle:@"修改" forState:UIControlStateNormal];
        btnSkip.hidden = YES;
        btnBottom.hidden = YES;
    }
    btnBottom.hidden = YES;
}

- (void)actionAgreement {
    WKWebViewController *vc = [[WKWebViewController alloc] initWithURLString:@"https://www.baidu.com/duty/"];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)actionSkip {
    NSDictionary *dicData;
    NSString *nickName = IsNilString(self.tf.text) == YES ? @"早安上海" : self.tf.text;
    
    if (self.isLogin) {//修改用户信息
        [SXLoadingView showAlertHUD:@"修改成功" duration:1];
        [self.navigationController popViewControllerAnimated:YES];
        
        dicData = @{@"mobile":[UserManager sharedUserManager].userInfo.mobile,
                    @"nickName":nickName,
                    @"avatarUrl":[UserManager sharedUserManager].userInfo.avatarUrl
                              };
        
        [PPNetworkHelper POST:URL_setUserInfo parameters:dicData success:^(id responseObject) {
            
        } failure:^(NSError *error) {
            [SXLoadingView showAlertHUD:SXLoadingErrorStr duration:SXLoadingTime];
        }];
        
        dicData = @{@"uid":[UserManager sharedUserManager].userInfo.uid,
                    @"mobile":[UserManager sharedUserManager].userInfo.mobile,
                    @"nickName":nickName,
                    @"avatarUrl":[UserManager sharedUserManager].userInfo.avatarUrl
                    };
    } else {
        
        dicData = @{@"mobile":self.usermobil,
                    @"nickName":nickName,
                    @"avatarUrl":self.userimage
                    };
        
        [SXLoadingView showAlertHUD:@"登录成功" duration:1];
        [PPNetworkHelper POST:URL_setUserInfo parameters:dicData success:^(id responseObject) {
            
        } failure:^(NSError *error) {
            [SXLoadingView showAlertHUD:SXLoadingErrorStr duration:SXLoadingTime];
        }];
        MainTabBarVC *vc = [[MainTabBarVC alloc] init];
        [UIApplication sharedApplication].keyWindow.rootViewController = vc;
        
        dicData = @{@"uid":self.uid,
                    @"mobile":self.usermobil,
                    @"nickName":nickName,
                    @"avatarUrl":self.userimage
                    };
    }
    [[UserManager sharedUserManager] updateUserInfo:dicData];
}

- (void)actionIcon {
    //创建UIImagePickerController对象，并设置代理和可编辑
    UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.editing = YES;
    imagePicker.delegate = self;
    imagePicker.allowsEditing = YES;
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction * photo = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //选择相册时，设置UIImagePickerController对象相关属性
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        //跳转到UIImagePickerController控制器弹出相册
        [self presentViewController:imagePicker animated:YES completion:nil];
    }];
    UIAlertAction * camera = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
#if TARGET_IPHONE_SIMULATOR  //模拟器
        [SXLoadingView showAlertHUD:@"模拟器不支持打开相机哦" duration:SXLoadingTime];
#elif TARGET_OS_IPHONE      //真机
        //选择相机时，设置UIImagePickerController对象相关属性
        imagePicker.sourceType =  UIImagePickerControllerSourceTypeCamera;
        imagePicker.modalPresentationStyle = UIModalPresentationFullScreen;
        imagePicker.mediaTypes = @[(NSString *)kUTTypeImage];
        imagePicker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
        //跳转到UIImagePickerController控制器弹出相机
        [self presentViewController:imagePicker animated:YES completion:nil];
#endif
    }];
    UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
    [alert addAction:photo];
    [alert addAction:camera];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:nil];
}
#pragma mark - imagePickerController delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    //获取到的图片
    UIImage * image = info[UIImagePickerControllerEditedImage];
    [self.btnUserIcon setImage:image forState:UIControlStateNormal];
    
//    [SXLoadingView showProgressHUD:nil];
    
//    [PPNetworkHelper setRequestSerializer:PPRequestSerializerHTTP];
//    [PPNetworkHelper uploadImagesWithURL:URL_upload parameters:nil name:@"userIcon" images:@[image] fileNames:@[@"imageFile.png"] imageScale:0.8f imageType:@"image/png" progress:^(NSProgress *progress) {
//    } success:^(id responseObject) {
//        self.userimage = responseObject[@"retBody"][@"filePath"];
//
//        [SXLoadingView showAlertHUD:responseObject[@"retMsg"] duration:SXLoadingTime];
//        if ([responseObject[@"success"] integerValue] == 1) {
//            [self.btnUserIcon setImage:image forState:UIControlStateNormal];
//        }
//    } failure:^(NSError *error) {
//        [SXLoadingView showAlertHUD:SXLoadingErrorStr duration:SXLoadingTime];
//    }];

//    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    //ContentType设置
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:
//                                                         @"application/json",
//                                                         @"text/json",
//                                                         @"text/javascript",
//                                                         @"text/html",
//                                                         @"text/plain",
//                                                         nil];
//    [manager POST:URL_upload parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
//        //把image  转为data , POST上传只能传data
//        NSData *data = UIImagePNGRepresentation(image);
//        //上传的参数(上传图片，以文件流的格式)
//        /**
//         *  FileData:要上传的文件的二进制数据
//         *  name:上传参数名称
//         *  fileName：上传到服务器的文件名称
//         *  mimeType：文件类型
//         */
//        [formData appendPartWithFileData:data
//                                    name:@"name"
//                                fileName:@"icon.png"
//                                mimeType:@"application/octet-stream"];
//    } progress:^(NSProgress * _Nonnull uploadProgress) {
//
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
//        NSLog(@"上传成功%@",dic);
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        NSLog(@"上传失败%@",error);
//    }];
}
#pragma mark - textField代理
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    NSUInteger proposedNewLength = textField.text.length - range.length + string.length;
    if (proposedNewLength >= self.textShortLength) {
        self.btnOK.alpha = 1;
        self.btnOK.userInteractionEnabled = YES;
    } else {
        self.btnOK.alpha = 0.6;
        self.btnOK.userInteractionEnabled = NO;
    }
    if (proposedNewLength > self.textLongLength) {
        return NO;//限制长度
    } else {
        return YES;
    }
}

- (void)textFieldDidEndEditing:(UITextField *)textField reason:(UITextFieldDidEndEditingReason)reason {
    if (textField.text.length == 0) {
        self.btnOK.alpha = 0.6;
        self.btnOK.userInteractionEnabled = NO;
    }
}


@end
